import { Component, Input, ViewEncapsulation, ChangeDetectionStrategy, ElementRef, TemplateRef } from '@angular/core';
import { InputBoolean, TypeUtils } from '../core/api';

@Component({
  selector: 'lv-form-label',
  templateUrl: './form-label.component.html',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    '[class.lv-form-label]': 'true',
    '[class.lv-form-label-required]': 'lvRequired',
    '[class.lv-form-label-colon]': 'true',
  },
})
export class FormLabelComponent {
  // 必选
  @Input() @InputBoolean() lvRequired: boolean = false;

  @Input() lvLabelTip: string | TemplateRef<void> = null;

  // 冒号
  _lvColon: boolean;

  // 非必选是否保留宽度
  _keepRequiredWidth: boolean;

  public typeUtils = TypeUtils;

  constructor(public elementRef: ElementRef) {
    // 把实例存DOM,便于lv-form检索
    this.elementRef.nativeElement.componentInstance = this;
  }

  get lvColon(): boolean {
    return this._lvColon;
  }

  get lvKeepRequiredWidth(): boolean {
    return this._keepRequiredWidth;
  }

  // 使用setter实现,立即使样式生效,避免和lv-form使用时1.出现ExpressionChangedAfterItHasBeenCheckedError 2.计算宽度不准
  @Input('lvColon')
  @InputBoolean()
  set lvColon(value: boolean) {
    this._lvColon = value;

    if (this._lvColon) {
      this.elementRef.nativeElement.classList.add('lv-form-label-colon');
    } else {
      this.elementRef.nativeElement.classList.remove('lv-form-label-colon');
    }
  }

  // 使用setter实现,立即使样式生效,避免和lv-form使用时1.出现ExpressionChangedAfterItHasBeenCheckedError 2.计算宽度不准
  @Input('lvKeepRequiredWidth')
  @InputBoolean()
  set lvKeepRequiredWidth(value: boolean) {
    this._keepRequiredWidth = value;

    if (this._keepRequiredWidth) {
      this.elementRef.nativeElement.classList.add('lv-form-label-required-width-keep');
    } else {
      this.elementRef.nativeElement.classList.remove('lv-form-label-required-width-keep');
    }
  }
}
